package com.zhongjian.technologycal.mall.activity.main.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.activity.LoginActivity;
import com.zhongjian.technologycal.mall.activity.main.bean.OrderHeads;
import com.zhongjian.technologycal.mall.activity.main.bean.OrderLines;
import com.zhongjian.technologycal.mall.activity.main.bean.OrderModelBean;
import com.zhongjian.technologycal.mall.activity.personal.activity.NewsAddressListActivity;
import com.zhongjian.technologycal.mall.activity.personal.activity.SettingPayPasswordActivity;
import com.zhongjian.technologycal.mall.base.BaseActivity;
import com.zhongjian.technologycal.mall.base.BaseContacts;
import com.zhongjian.technologycal.mall.bean.AddressComBean;
import com.zhongjian.technologycal.mall.bean.BaseBean;
import com.zhongjian.technologycal.mall.bean.OrderCommitBean;
import com.zhongjian.technologycal.mall.bean.PayBean;
import com.zhongjian.technologycal.mall.bean.ProductDetailsBean;
import com.zhongjian.technologycal.mall.bean.UserInfoBean;
import com.zhongjian.technologycal.mall.net.HttpRetrofitClient;
import com.zhongjian.technologycal.mall.utils.AppTools;
import com.zhongjian.technologycal.mall.utils.LoadingDialog;
import com.zhongjian.technologycal.mall.utils.LogUtils;
import com.zhongjian.technologycal.mall.utils.NetWorkUtils;
import com.zhongjian.technologycal.mall.utils.ToastUitl;
import com.zhongjian.technologycal.mall.utils.UserUtils;
import com.zhongjian.technologycal.mall.view.EaseSwitchButton;
import com.zhongjian.technologycal.mall.view.PasswordInputView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.drakeet.materialdialog.MaterialDialog;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import rx.Subscriber;


/**
 * 实现订单结算页面
 * Created by wei on 2017/11/29.
 *
 * @author wei
 *         依照顺序1：现金红包(Coupon) 2：购物币(RemainPoints) 3：现金币(RemainElecNum)  4：消费积分(RemainVIPAmount)
 */

public class PaymentOrderActivity extends BaseActivity {
    @BindView(R.id.iv_back_page)
    ImageView iv_back_page;
    @BindView(R.id.tv_main_title)
    TextView tv_main_title;
    @BindView(R.id.switch_owner_leavel)
    EaseSwitchButton switch_owner_leavel;
    @BindView(R.id.switch_owner_leavel2)
    EaseSwitchButton switch_owner_leavel2;
    @BindView(R.id.switch_owner_leavel3)
    EaseSwitchButton switch_owner_leavel3;
    @BindView(R.id.switch_owner_leavel4)
    EaseSwitchButton switch_owner_leavel4;
    @BindView(R.id.ll_add_address)
    LinearLayout ll_add_address;
    @BindView(R.id.order_iv_heading_photo)
    ImageView order_iv_heading_photo;
    @BindView(R.id.address_tv_name)
    TextView address_tv_name;
    @BindView(R.id.address_tv_phone)
    TextView address_tv_phone;
    @BindView(R.id.address_tv_details)
    TextView address_tv_details;
    @BindView(R.id.payment_tv_product_name)
    TextView payment_tv_product_name;
    @BindView(R.id.payment_tv_product_price)
    TextView payment_tv_product_price;
    @BindView(R.id.payment_tv_product_count)
    TextView payment_tv_product_count;
    @BindView(R.id.shopping_tv_total_price)
    TextView shopping_tv_total_price;
    private ProductDetailsBean productDetailsBean;
    private OrderCommitBean orderCommitBean;
    @BindView(R.id.use_tv_Coupon)
    TextView use_tv_Coupon;
    @BindView(R.id.use_tv_RemainPoints)
    TextView use_tv_RemainPoints;
    @BindView(R.id.use_tv_RemainElecNum)
    TextView use_tv_RemainElecNum;
    @BindView(R.id.use_tv_RemainVIPAmount)
    TextView use_tv_RemainVIPAmount;
    @BindView(R.id.payment_tv_product_sapceName)
    TextView payment_tv_product_sapceName;

    @BindView(R.id.tv_tatol_money)
    TextView tv_tatol_money;
    @BindView(R.id.deduction_tv_Coupon)
    TextView deduction_tv_Coupon;
    @BindView(R.id.deduction_tv_RemainElecNum)
    TextView deduction_tv_RemainElecNum;
    @BindView(R.id.deduction_tv_RemainPoints)
    TextView deduction_tv_RemainPoints;
    @BindView(R.id.deduction_tv_RemainVIPAmount)
    TextView deduction_tv_RemainVIPAmount;

    @BindView(R.id.shopping_et_content)
    EditText shopping_et_content;

    @BindView(R.id.use_ll_RemainVIPAmount)
    LinearLayout use_ll_RemainVIPAmount;
    @BindView(R.id.deduction_ll_RemainVIPAmount)
    LinearLayout deduction_ll_RemainVIPAmount;

    private int REQUESTCODE = 1001;

    private String spId;
    private String pname;
    private String pprice;
    private String pnum;
    private String productId;
    private double realPrice;
    private String mProducername;
    private String mProducerno;
    private String mProducertel;
    private int addressId;
    private double elecNum;
    private String elecNum1;
    private double tatolMoney;
    // -----------------------------------
    private double coupon2 = 0;//现金红包
    private double coupon;//现金红包
    private double remainPoints;//购物币
    private double remainElecNum;//现金币
    private double remainVIPAmount;//用户可用消费积分

    private double coupon1 = 0;//现金红包
    private double remainElecNum1 = 0;//现金币
    private double remainPoints1 = 0;//购物币
    private double remainVIPAmount1 = 0;//实付消费积分
    private double remainVIPAmount2 = 0;//商品可用消费积分

    private Dialog payDialog = null;
    private String orderNoC;
    private boolean isNoAddress = false;
    private String spaceName;
    private boolean isBeLongToVIP;
    private String userName;
    private MaterialDialog mMaterialDialog = null;

    @Override
    protected void beforeInit() {
        super.beforeInit();
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_payment_order;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tv_main_title.setText("确认订单");
        pnum = getIntent().getStringExtra("pnum");
        productId = getIntent().getStringExtra("productId");
        pprice = getIntent().getStringExtra("sprice");
        pname = getIntent().getStringExtra("pname");
        spId = getIntent().getStringExtra("spid");
        elecNum1 = getIntent().getStringExtra("elecNum");
        elecNum = Double.valueOf(elecNum1) * Double.valueOf(pnum);
        isBeLongToVIP = getIntent().getBooleanExtra("isBeLongToVIP", false);
        spaceName = getIntent().getStringExtra("spaceName");

//        StatusBarUtil.setColorNoTranslucent(this, getResources().getColor(R.color.border_color));
//        StatusBarUtil.setMiuiStatusBarDarkMode(this, true);
        initViewRequestProductDetails();
        initViewPersonInfo();
        initViewData();
        switch_owner_leavel.closeSwitch();
        switch_owner_leavel2.closeSwitch();
        switch_owner_leavel3.closeSwitch();
        switch_owner_leavel4.closeSwitch();
        computeCount();
        if (isBeLongToVIP == true) {
            use_ll_RemainVIPAmount.setVisibility(View.VISIBLE);
            deduction_ll_RemainVIPAmount.setVisibility(View.VISIBLE);
            switchOpenVip();

        } else {
            use_ll_RemainVIPAmount.setVisibility(View.GONE);
            deduction_ll_RemainVIPAmount.setVisibility(View.GONE);
            switchOpen();
        }

    }

    /**
     * 非Vip
     */
    private void switchOpen() {
        switch_owner_leavel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (switch_owner_leavel.isSwitchOpen()) {
                    switch_owner_leavel.closeSwitch();
                    computeCount();

                } else {
                    switch_owner_leavel.openSwitch();
                    computeCount();
                }
            }
        });
        switch_owner_leavel2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (switch_owner_leavel2.isSwitchOpen()) {
                    switch_owner_leavel2.closeSwitch();
                    computeCount();

                } else if (switch_owner_leavel2.isSwitchClose()) {
                    switch_owner_leavel2.openSwitch();
                    computeCount();

                }
            }
        });
        switch_owner_leavel3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (switch_owner_leavel3.isSwitchOpen()) {
                    switch_owner_leavel3.closeSwitch();
                    computeCount();
                } else {
                    switch_owner_leavel3.openSwitch();
                    computeCount();

                }
            }
        });

    }

    /**
     * Vip积分抵扣
     */
    private void switchOpenVip() {
        switch_owner_leavel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (switch_owner_leavel.isSwitchOpen()) {
                    switch_owner_leavel.closeSwitch();
                    computeCount();
                    initViewIsOpen();
                } else {
                    switch_owner_leavel.openSwitch();
                    switch_owner_leavel4.closeSwitch();
                    computeCount();
                    initViewIsOpen();
                }
            }
        });
        switch_owner_leavel2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (switch_owner_leavel2.isSwitchOpen()) {
                    switch_owner_leavel2.closeSwitch();
                    initViewIsOpen();
                    computeCount();
                } else if (switch_owner_leavel2.isSwitchClose()) {
                    switch_owner_leavel2.openSwitch();
                    switch_owner_leavel4.closeSwitch();
                    computeCount();
                    initViewIsOpen();

                }
            }
        });

        switch_owner_leavel3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (switch_owner_leavel3.isSwitchOpen()) {
                    switch_owner_leavel3.closeSwitch();
                    computeCount();
                    initViewIsOpen();
                } else {
                    switch_owner_leavel3.openSwitch();
                    switch_owner_leavel4.closeSwitch();
                    computeCount();
                    initViewIsOpen();
                }
            }
        });

        switch_owner_leavel4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (switch_owner_leavel4.isSwitchOpen()) {
                    switch_owner_leavel4.closeSwitch();
                    initViewIsOpen();
                    computeCount();
                } else {
                    switch_owner_leavel4.openSwitch();
                    initViewIsOpen();
                    computeCount();
//                    computeRemainVIPAmount();
                }
            }


        });

    }

    /**
     * 初始化数据
     */
    private void initViewData() {
        payment_tv_product_name.setText(pname);
        payment_tv_product_price.setText("￥" + String.format(pprice));
        payment_tv_product_count.setText("" + pnum);
        tatolMoney = Double.valueOf(pprice) * Double.valueOf(pnum);
        realPrice = Double.valueOf(pprice) * Double.valueOf(pnum);
        shopping_tv_total_price.setText("￥" + realPrice + "元");
        tv_tatol_money.setText("¥" + tatolMoney);
        coupon = Double.valueOf(elecNum) / 2;
        remainVIPAmount2 = Double.valueOf(elecNum);
        payment_tv_product_sapceName.setText("规格：" + spaceName);
    }

    private void initViewIsOpen() {
        if (switch_owner_leavel4.isSwitchOpen()) {
            switch_owner_leavel.closeSwitch();
            switch_owner_leavel2.closeSwitch();
            switch_owner_leavel3.closeSwitch();
        } else if (switch_owner_leavel.isSwitchOpen() || switch_owner_leavel2.isSwitchOpen() || switch_owner_leavel3.isSwitchOpen()) {
            switch_owner_leavel4.closeSwitch();
        }

    }


    /**
     * 计算抵扣/精度计算
     */
    private void computeCount() {
        if (switch_owner_leavel4.isSwitchOpen()) {
            double realPrice3 = tatolMoney;
            double realConpon3 = 0;
            double realPoints3 = 0;
            double realElecNum3 = 0;
            coupon1 = realConpon3;
            remainPoints1 = realPoints3;
            remainElecNum1 = realElecNum3;
            if (remainVIPAmount >= remainVIPAmount2) {
                remainVIPAmount1 = remainVIPAmount2;
                realPrice =  AppTools.sub(realPrice3,remainVIPAmount2);
            } else {
                remainVIPAmount1 = remainVIPAmount;
                realPrice = AppTools.sub(realPrice3,remainVIPAmount);
            }


        } else if (switch_owner_leavel.isSwitchOpen() && switch_owner_leavel2.isSwitchOpen()
                && switch_owner_leavel3.isSwitchOpen()) {
            double realPrice3 = tatolMoney;
            double realConpon3 = 0;
            double realPoints3 = 0;
            double realElecNum3 = 0;
            if (coupon2 >= coupon) {
                realConpon3 = coupon;
                realPrice3 = AppTools.sub(realPrice3,realConpon3);
            } else {
                realConpon3 = coupon2;
                realPrice3 = AppTools.sub(realPrice3,realConpon3);
            }
            coupon1 = realConpon3;
            if (remainPoints >= realPrice3) {
                realPoints3 = realPrice3;
                realPrice3 = 0;
            } else {
                realPoints3 = remainPoints;
                realPrice3 = AppTools.sub(realPrice3,realPoints3);
            }
            remainPoints1 = realPoints3;
            if (remainElecNum >= realPrice3) {
                realElecNum3 = realPrice3;
                realPrice3 = 0;
            } else {
                realElecNum3 = remainElecNum;
                realPrice3 = AppTools.sub(realPrice3,realElecNum3);
            }
            remainElecNum1 = realElecNum3;
            realPrice = realPrice3;
            remainVIPAmount1 = 0;

        } else if (switch_owner_leavel.isSwitchOpen() && switch_owner_leavel2.isSwitchOpen()
                && switch_owner_leavel3.isSwitchClose()) {
            double realPrice3 = tatolMoney;
            double realConpon3 = 0;
            double realPoints3 = 0;
            double realElecNum3 = 0;
            if (coupon2 >= coupon) {
                realConpon3 = coupon;
                realPrice3 = AppTools.sub(realPrice3,realConpon3);
            } else {
                realConpon3 = coupon2;
                realPrice3 = AppTools.sub(realPrice3,realConpon3);
            }
            coupon1 = realConpon3;

            if (remainPoints >= realPrice3) {
                realPoints3 = realPrice3;
                realPrice3 = 0;
            } else {
                realPoints3 = remainPoints;
                realPrice3 = AppTools.sub(realPrice3,realPoints3);
            }
            remainPoints1 = realPoints3;
            remainElecNum1 = realElecNum3;
            realPrice = realPrice3;
            remainVIPAmount1 = 0;

        } else if (switch_owner_leavel.isSwitchOpen() && switch_owner_leavel2.isSwitchClose()
                && switch_owner_leavel3.isSwitchClose()) {
            double realPrice3 = tatolMoney;
            double realConpon3 = 0;
            double realPoints3 = 0;
            double realElecNum3 = 0;
            if (coupon2 >= coupon) {
                realConpon3 = coupon;
                realPrice3 = AppTools.sub(realPrice3,realConpon3);
            } else {
                realConpon3 = coupon2;
                realPrice3 = AppTools.sub(realPrice3,realConpon3);
            }
            coupon1 = realConpon3;
            remainPoints1 = realPoints3;
            remainElecNum1 = realElecNum3;
            realPrice = realPrice3;
            remainVIPAmount1 = 0;

        } else if (switch_owner_leavel.isSwitchClose() && switch_owner_leavel2.isSwitchOpen()
                && switch_owner_leavel3.isSwitchOpen()) {
            double realPrice3 = tatolMoney;
            double realConpon3 = 0;
            double realPoints3 = 0;
            double realElecNum3 = 0;
            coupon1 = realConpon3;
            if (remainPoints >= realPrice3) {
                realPoints3 = realPrice3;
                realPrice3 = 0;
            } else {
                realPoints3 = remainPoints;
                realPrice3 = AppTools.sub(realPrice3,realPoints3);
            }
            remainPoints1 = realPoints3;
            if (remainElecNum >= realPrice3) {
                realElecNum3 = realPrice3;
                realPrice3 = 0;
            } else {
                realElecNum3 = remainElecNum;
                realPrice3 = AppTools.sub(realPrice3,realElecNum3);

            }
            remainElecNum1 = realElecNum3;
            realPrice = realPrice3;
            remainVIPAmount1 = 0;

        } else if (switch_owner_leavel.isSwitchClose() && switch_owner_leavel2.isSwitchClose()
                && switch_owner_leavel3.isSwitchOpen()) {
            double realPrice3 = tatolMoney;
            double realConpon3 = 0;
            double realPoints3 = 0;
            double realElecNum3 = 0;
            coupon1 = realConpon3;
            remainPoints1 = realPoints3;
            if (remainElecNum >= realPrice3) {
                realElecNum3 = realPrice3;
                realPrice3 = 0;
            } else {
                realElecNum3 = remainElecNum;
                realPrice3 = AppTools.sub(realPrice3,realElecNum3);
            }
            remainElecNum1 = realElecNum3;
            realPrice = realPrice3;
            remainVIPAmount1 = 0;

        } else if (switch_owner_leavel.isSwitchClose() && switch_owner_leavel2.isSwitchClose()
                && switch_owner_leavel3.isSwitchClose()) {
            coupon1 = 0;
            remainElecNum1 = 0;
            remainPoints1 = 0;
            realPrice = tatolMoney;
            remainVIPAmount1 = 0;
        } else if (switch_owner_leavel.isSwitchOpen() && switch_owner_leavel2.isSwitchClose()
                && switch_owner_leavel3.isSwitchOpen()) {
            double realPrice3 = tatolMoney;
            double realConpon3 = 0;
            double realPoints3 = 0;
            double realElecNum3 = 0;
            if (coupon2 >= coupon) {
                realConpon3 = coupon;
                realPrice3 =  AppTools.sub(realPrice3,realConpon3);
            } else {
                realConpon3 = coupon2;
                realPrice3 =  AppTools.sub(realPrice3,realConpon3);
            }
            coupon1 = realConpon3;
            remainPoints1 = realPoints3;
            if (remainElecNum >= realPrice3) {
                realElecNum3 = realPrice3;
                realPrice3 = 0;
            } else {
                realElecNum3 = remainElecNum;
                realPrice3 = AppTools.sub(realPrice3,realElecNum3);
            }
            remainElecNum1 = realElecNum3;
            realPrice = realPrice3;
            remainVIPAmount1 = 0;

        } else if (switch_owner_leavel.isSwitchClose() && switch_owner_leavel2.isSwitchOpen()
                && switch_owner_leavel3.isSwitchClose()) {
            double realPrice3 = tatolMoney;
            double realConpon3 = 0;
            double realPoints3 = 0;
            double realElecNum3 = 0;
            coupon1 = realConpon3;

            if (remainPoints >= realPrice3) {
                realPoints3 = realPrice3;
                realPrice3 = 0;
            } else {
                realPoints3 = remainPoints;
                realPrice3 = AppTools.sub(realPrice3,realPoints3);
            }
            remainPoints1 = realPoints3;
            remainElecNum1 = realElecNum3;
            realPrice = realPrice3;
            remainVIPAmount1 = 0;

        }
        deduction_tv_Coupon.setText("- ¥" + coupon1);
        deduction_tv_RemainElecNum.setText("- ¥" + remainElecNum1);
        deduction_tv_RemainPoints.setText("- ¥" + remainPoints1);
        shopping_tv_total_price.setText("￥" + realPrice + "元");
        deduction_tv_RemainVIPAmount.setText("- ¥" + remainVIPAmount1);
    }


    /**
     * 收货地址选择|添加新地址
     */
    @OnClick(R.id.ll_add_address)
    public void onClickAddAddress() {
        Intent intent = new Intent();
        intent.setClass(getBaseContext(), NewsAddressListActivity.class);
        startActivityForResult(intent, REQUESTCODE);
    }

    /**
     * 默认地址获取
     */
    @Override
    public void initPresenter() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext()).postUrlRequest(UserUtils.getUserToken(),
                new Subscriber<ResponseBody>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        LoadingDialog.showDialogForLoading(PaymentOrderActivity.this);
                    }

                    @Override
                    public void onCompleted() {
                        LoadingDialog.cancelDialogForLoading();

                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.logd("error", e.getMessage());
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        LoadingDialog.cancelDialogForLoading();
                        try {
                            Gson gson = new Gson();
                            AddressComBean userAddressBean = gson.fromJson(responseBody.string(), AddressComBean.class);
                            if (userAddressBean.getError_code() == 0) {
                                isNoAddress = true;
                                address_tv_name.setText(userAddressBean.getData().getName());
                                address_tv_phone.setText(userAddressBean.getData().getPhone());
                                address_tv_details.setText(
                                        userAddressBean.getData().getProvinceName()
                                                + userAddressBean.getData().getCityName()
                                                + userAddressBean.getData().getRegionName()
                                                + userAddressBean.getData().getDetailAddress());
                                addressId = userAddressBean.getData().getId();
                            } else if (userAddressBean.getError_code() == 3) {
                                Intent intent = new Intent();
                                intent.setAction("com.broadcast.info_out_line");
                                sendBroadcast(intent);
                            } else if (userAddressBean.getError_code() == -1) {
                                isNoAddress = false;
                            } else {
                                ToastUitl.showShort(userAddressBean.getError_message());
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }
                });


    }

    /**
     * 订单提交
     */
    private void initViewRequestCommit() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        OrderModelBean orderModelBean = new OrderModelBean();
        orderModelBean.setAdrressId(addressId);
        List<OrderHeads> listPersons = new ArrayList<>();
        //
        OrderHeads orderHeads = new OrderHeads();
        orderHeads.setMemo(shopping_et_content.getText().toString().trim());
        orderHeads.setProducername(mProducername);
        orderHeads.setRealPay(realPrice);
        orderHeads.setUseElecNum(remainElecNum1);
        orderHeads.setUseCoupon(coupon1);
        orderHeads.setFreight(0);
        orderHeads.setProducerno(mProducerno);
        orderHeads.setProducertel(mProducertel);
        orderHeads.setUseVIPRemainNum(remainVIPAmount1);
        orderHeads.setUsePointNum(remainPoints1);
        orderHeads.setTotalAmount(tatolMoney);
        //
        List<OrderLines> listSchoolInfo1 = new ArrayList<>();
        OrderLines orderLines = new OrderLines();
        orderLines.setProductNum(Integer.valueOf(pnum));
        orderLines.setProductId(Integer.valueOf(productId));
        orderLines.setSpecId(Integer.valueOf(spId));
        listSchoolInfo1.add(orderLines);
        orderHeads.setOrderLines(listSchoolInfo1);
        //
        listPersons.add(orderHeads);//
        orderModelBean.setOrderHeads(listPersons);
        Gson gson = new Gson();
        RequestBody body = RequestBody.create(
                okhttp3.MediaType.parse("application/json; charset=utf-8"), gson.toJson(orderModelBean));

        HttpRetrofitClient.getInstance(getBaseContext())
                .getUrlRequestCommit(
                        UserUtils.getUserToken(), body,
                        new Subscriber<ResponseBody>() {
                            @Override
                            public void onStart() {
                                super.onStart();
                                LoadingDialog.showDialogForLoading(PaymentOrderActivity.this);
                            }
                            @Override
                            public void onCompleted() {
                                LoadingDialog.cancelDialogForLoading();
                            }

                            @Override
                            public void onError(Throwable e) {
                                LoadingDialog.cancelDialogForLoading();
                            }

                            @Override
                            public void onNext(ResponseBody responseBody) {
                                LoadingDialog.cancelDialogForLoading();
                                try {
                                    Gson gson = new Gson();
                                    PayBean payBean = gson.fromJson(responseBody.string(), PayBean.class);
                                    if (payBean.getError_code() == 0) {
                                        if (payBean.getData().getType().equals("1")) {
                                            orderNoC = payBean.getData().getOrderNoC();
                                            payDialog = new Dialog(PaymentOrderActivity.this, R.style.dialog_style1);
                                            LinearLayout layout;
                                            LayoutInflater inflater = (LayoutInflater) PaymentOrderActivity.this
                                                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                                            layout = (LinearLayout) inflater.inflate(R.layout.dialog_hint,
                                                    null);
                                            final PasswordInputView tv_hint = (PasswordInputView) layout
                                                    .findViewById(R.id.again_paypswd_pet);
                                            layout.findViewById(R.id.dialog_btn_cancel).setOnClickListener(
                                                    new View.OnClickListener() {

                                                        @Override
                                                        public void onClick(View v) {
                                                            finish();
                                                            payDialog.dismiss();
                                                        }
                                                    });
                                            layout.findViewById(R.id.dialog_btn_ensure).setOnClickListener(
                                                    new View.OnClickListener() {
                                                        @Override
                                                        public void onClick(View view) {
                                                            if (TextUtils.isEmpty(tv_hint.getText().toString().trim())) {
                                                                ToastUitl.showShort("支付密码不能为空");
                                                                return;
                                                            } else if (tv_hint.getText().toString().trim().length() < 6) {
                                                                ToastUitl.showShort("请输入6位的支付密码");
                                                                return;
                                                            }
                                                            initRequestPayPassword(tv_hint.getText().toString().trim());
                                                        }
                                                    });
                                            payDialog.setContentView(layout);
                                            payDialog.show();

                                        } else if (payBean.getData().getType().equals("2")) {
                                            Intent intent = new Intent();
                                            intent.setClass(getBaseContext(), PayOrderItemsActivity.class);
                                            intent.putExtra("singData", payBean.getData().getSingData());
                                            startActivity(intent);
                                            finish();
                                        } else if (payBean.getData().getType().equals("3")) {
                                            Intent intent = new Intent();
                                            intent.setClass(getBaseContext(), PayOrderItemsActivity.class);
                                            intent.putExtra("singData", payBean.getData().getSingData());
                                            startActivity(intent);
                                            finish();
                                        } else {
                                            ToastUitl.showShort(payBean.getError_message());
                                        }
                                    } else if (payBean.getError_code() == 3) {
                                        Intent intent = new Intent();
                                        intent.setAction("com.broadcast.info_out_line");
                                        sendBroadcast(intent);
                                    } else {
                                        ToastUitl.showShort(payBean.getError_message());
                                    }


                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        });

    }

    /**
     * 带有积分订单提交
     */
    private void initViewRequestVipCommit() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        OrderModelBean orderModelBean = new OrderModelBean();
        orderModelBean.setAdrressId(addressId);
        List<OrderHeads> listPersons = new ArrayList<>();
        //
        OrderHeads orderHeads = new OrderHeads();
        orderHeads.setMemo(shopping_et_content.getText().toString().trim());
        orderHeads.setProducername(mProducername);
        orderHeads.setRealPay(realPrice);
        orderHeads.setUseElecNum(remainElecNum1);
        orderHeads.setUseCoupon(coupon1);
        orderHeads.setFreight(0);
        orderHeads.setProducerno(mProducerno);
        orderHeads.setProducertel(mProducertel);
        orderHeads.setUseVIPRemainNum(remainVIPAmount1);
        orderHeads.setUsePointNum(remainPoints1);
        orderHeads.setTotalAmount(tatolMoney);
        //
        List<OrderLines> listSchoolInfo1 = new ArrayList<>();
        OrderLines orderLines = new OrderLines();
        orderLines.setProductNum(Integer.valueOf(pnum));
        orderLines.setProductId(Integer.valueOf(productId));
        orderLines.setSpecId(Integer.valueOf(spId));
        listSchoolInfo1.add(orderLines);
        orderHeads.setOrderLines(listSchoolInfo1);
        //
        listPersons.add(orderHeads);//
        orderModelBean.setOrderHeads(listPersons);
        Gson gson = new Gson();
        RequestBody body = RequestBody.create(
                okhttp3.MediaType.parse("application/json; charset=utf-8"), gson.toJson(orderModelBean));

        HttpRetrofitClient.getInstance(getBaseContext())
                .getUrlRequestCommit(
                        UserUtils.getUserToken(), body,
                        new Subscriber<ResponseBody>() {
                            @Override
                            public void onStart() {
                                super.onStart();
                                LoadingDialog.showDialogForLoading(PaymentOrderActivity.this);
                            }

                            @Override
                            public void onCompleted() {
                                LoadingDialog.cancelDialogForLoading();

                            }

                            @Override
                            public void onError(Throwable e) {
                                LoadingDialog.cancelDialogForLoading();

                            }

                            @Override
                            public void onNext(ResponseBody responseBody) {
                                LoadingDialog.cancelDialogForLoading();
                                try {
                                    Gson gson = new Gson();
                                    PayBean payBean = gson.fromJson(responseBody.string(), PayBean.class);
                                    if (payBean.getError_code() == 0) {
                                        if (payBean.getData().getType().equals("1")) {
                                            orderNoC = payBean.getData().getOrderNoC();
                                            payDialog = new Dialog(PaymentOrderActivity.this, R.style.dialog_style1);
                                            LinearLayout layout;
                                            LayoutInflater inflater = (LayoutInflater) PaymentOrderActivity.this
                                                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                                            layout = (LinearLayout) inflater.inflate(R.layout.dialog_hint,
                                                    null);
                                            final PasswordInputView tv_hint = (PasswordInputView) layout
                                                    .findViewById(R.id.again_paypswd_pet);
                                            layout.findViewById(R.id.dialog_btn_cancel).setOnClickListener(
                                                    new View.OnClickListener() {

                                                        @Override
                                                        public void onClick(View v) {
                                                            finish();
                                                            payDialog.dismiss();
                                                        }
                                                    });
                                            layout.findViewById(R.id.dialog_btn_ensure).setOnClickListener(
                                                    new View.OnClickListener() {
                                                        @Override
                                                        public void onClick(View view) {
                                                            if (TextUtils.isEmpty(tv_hint.getText().toString().trim())) {
                                                                ToastUitl.showShort("支付密码不能为空");
                                                                return;
                                                            } else if (tv_hint.getText().toString().trim().length() < 6) {
                                                                ToastUitl.showShort("请输入6位的支付密码");
                                                                return;
                                                            }
                                                            initRequestPayPassword(tv_hint.getText().toString().trim());

                                                        }
                                                    });
                                            payDialog.setContentView(layout);
                                            payDialog.show();

                                        } else if (payBean.getData().getType().equals("2")) {
                                            Intent intent = new Intent();
                                            intent.setClass(getBaseContext(), PayOrderItemsActivity.class);
                                            intent.putExtra("singData", payBean.getData().getSingData());
                                            startActivity(intent);
                                            finish();
                                        } else if (payBean.getData().getType().equals("3")) {
                                            Intent intent = new Intent();
                                            intent.setClass(getBaseContext(), PayOrderItemsActivity.class);
                                            intent.putExtra("singData", payBean.getData().getSingData());
                                            startActivity(intent);
                                            finish();
                                        } else {
                                            ToastUitl.showShort(payBean.getError_message());
                                        }
                                    } else if (payBean.getError_code() == 3) {
                                        Intent intent = new Intent();
                                        intent.setAction("com.broadcast.info_out_line");
                                        sendBroadcast(intent);
                                    } else {
                                        ToastUitl.showShort(payBean.getError_message());
                                    }


                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        });

    }


    /**
     * 获取商品详情数据
     */
    private void initViewRequestProductDetails() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext())
                .getUrlRequestProductDetails(
                        Integer.valueOf(productId),
                        new Subscriber<ResponseBody>() {
                            @Override
                            public void onStart() {
                                super.onStart();
//                                    LoadingDialog.showDialogForLoading(PaymentOrderActivity.this);
                            }

                            @Override
                            public void onCompleted() {
//                                    LoadingDialog.cancelDialogForLoading();

                            }

                            @Override
                            public void onError(Throwable e) {
//                                    LoadingDialog.cancelDialogForLoading();
                                ToastUitl.showShort(e.getMessage());
                            }

                            @Override
                            public void onNext(ResponseBody responseBody) {
//                                    LoadingDialog.cancelDialogForLoading();
                                try {
                                    Gson gson = new Gson();
                                    productDetailsBean =
                                            gson.fromJson(responseBody.string(), ProductDetailsBean.class);
                                    if (productDetailsBean.getError_code() == 0) {
                                        Picasso.get().load(BaseContacts.BASE_URL +
                                                productDetailsBean.getData().getProduct().getProductphotos().get(0).getPhoto())
                                                .into(order_iv_heading_photo);
                                        mProducername = productDetailsBean.getData().getProduct().getProducername();
                                        mProducerno = productDetailsBean.getData().getProduct().getProducerno();
                                        mProducertel = productDetailsBean.getData().getProduct().getProducertel();
                                    }else{
                                        ToastUitl.showShort(productDetailsBean.getError_message());
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        });


    }

    /**
     * 获取钱包数据
     */
    private void initViewPersonInfo() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext()).getUrlRequestAccountBalance(UserUtils.getUserToken(),
                new Subscriber<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUitl.showShort(e.getMessage());
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            Gson gson = new Gson();
                            UserInfoBean userInfoBean = gson.fromJson(responseBody.string(), UserInfoBean.class);
                            if (userInfoBean.getError_code() == 0) {
                                userName = userInfoBean.getData().getPersonDataMap().getUserName();
                                coupon2 = userInfoBean.getData().getPersonDataMap().getCoupon();
                                remainElecNum = userInfoBean.getData().getPersonDataMap().getRemainElecNum();
                                remainPoints = userInfoBean.getData().getPersonDataMap().getRemainPoints();
                                remainVIPAmount = userInfoBean.getData().getPersonDataMap().getRemainVIPAmount();
                                use_tv_Coupon.setText("可用现金红包" + coupon2);
                                use_tv_RemainElecNum.setText("可用现金币" + remainElecNum);
                                use_tv_RemainPoints.setText("可用购物币" + remainPoints);
                                use_tv_RemainVIPAmount.setText("可用消费积分" + remainVIPAmount);
                            } else if(userInfoBean.getError_code() == 3){
                                Intent intent = new Intent();
                                intent.setAction("com.broadcast.info_out_line");
                                sendBroadcast(intent);
                            }else{
                                ToastUitl.showShort(userInfoBean.getError_message());
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });


    }

    /**
     * 验证支付密码
     *
     * @param password
     */

    private void initRequestPayPassword(String password) {

        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext())
                .postUrlRequestPayPassword(UserUtils.getUserToken(),
                        password, new Subscriber<ResponseBody>() {
                            @Override
                            public void onStart() {
                                super.onStart();
                            }

                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(ResponseBody responseBody) {
                                try {
                                    Gson gson = new Gson();
                                    BaseBean baseBean = gson.fromJson(responseBody.string(), BaseBean.class);
                                    if (baseBean.getError_code() == 0) {
                                        ToastUitl.showShort(baseBean.getError_message());
                                        initRequestPayOrderNoC(orderNoC);
                                        payDialog.dismiss();
                                    } else if (baseBean.getError_code() == -1) {
                                        Intent intent = new Intent();
                                        intent.setClass(getBaseContext(), SettingPayPasswordActivity.class);
                                        intent.putExtra("username", userName);
                                        startActivity(intent);
                                        ToastUitl.showShort(baseBean.getError_message());
                                        payDialog.dismiss();
                                        finish();
                                        /**
                                         * 冻结
                                         */
                                    } else if (baseBean.getError_code() == 5) {
                                        ToastUitl.showShort(baseBean.getError_message());
                                        payDialog.dismiss();
                                        /**
                                         * 密码错误
                                         */
                                    } else if (baseBean.getError_code() == 1) {
                                        ToastUitl.showShort(baseBean.getError_message());
                                    } else if (baseBean.getError_code() == 3) {
                                        Intent intent = new Intent();
                                        intent.setAction("com.broadcast.info_out_line");
                                        sendBroadcast(intent);
                                    } else {
                                        ToastUitl.showShort(baseBean.getError_message());
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }


                            }
                        });

    }

    /**
     * 同步处理支付父订单
     *
     * @param
     */

    private void initRequestPayOrderNoC(String orderNoC) {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext())
                .postUrlRequestgetPayOrderC(UserUtils.getUserToken(),
                        orderNoC, new Subscriber<ResponseBody>() {
                            @Override
                            public void onStart() {
                                super.onStart();
                            }

                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {
                                ToastUitl.showShort(e.getMessage());

                            }

                            @Override
                            public void onNext(ResponseBody responseBody) {
                                try {
                                    Gson gson = new Gson();
                                    BaseBean baseBean = gson.fromJson(responseBody.string(), BaseBean.class);
                                    if (baseBean.getError_code() == 0) {
                                        ToastUitl.showShort(baseBean.getError_message());
                                        finish();
                                    } else if(baseBean.getError_code() == 3){
                                        Intent intent = new Intent();
                                        intent.setAction("com.broadcast.info_out_line");
                                        sendBroadcast(intent);
                                    }else {
                                        ToastUitl.showShort(baseBean.getError_message());
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }


                            }
                        });

    }

    @OnClick(R.id.panel_ll_ticket)
    public void onClickTicket() {

    }

    /**
     * 提交订单
     */
    @OnClick(R.id.tv_order_commit)
    public void onClickOrderCommit() {
        Intent intent = new Intent();
        if (UserUtils.getUserToken() == null || UserUtils.getUserToken().equals("")) {
            ToastUitl.showShort("请登录后才能提交订单～");
            intent.setClass(getBaseContext(), LoginActivity.class);
            startActivity(intent);
        } else {
            if (isNoAddress == true) {
                if (isBeLongToVIP == true) {
                    mMaterialDialog = new MaterialDialog(mContext)
                            .setMessage("您确定要购买此商品吗？")
                            .setPositiveButton("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    initViewRequestVipCommit();
                                    mMaterialDialog.dismiss();
                                }
                            })
                            .setNegativeButton("取消", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    mMaterialDialog.dismiss();
                                }
                            });
                    mMaterialDialog.setCanceledOnTouchOutside(true);
                    mMaterialDialog.show();
                } else {
                    mMaterialDialog = new MaterialDialog(mContext)
                            .setMessage("您确定要购买此商品吗？")
                            .setPositiveButton("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    initViewRequestCommit();
                                    mMaterialDialog.dismiss();
                                }
                            })
                            .setNegativeButton("取消", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    mMaterialDialog.dismiss();
                                }
                            });
                    mMaterialDialog.setCanceledOnTouchOutside(true);
                    mMaterialDialog.show();
                }

            } else {
                ToastUitl.showShort("请先选择或者添加收货地址！");
            }

        }

    }

    @OnClick(R.id.iv_back_page)
    public void onClickBack() {
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE && resultCode == 1002) {
            isNoAddress = true;
            address_tv_name.setText(data.getStringExtra("Name"));
            address_tv_phone.setText(data.getStringExtra("Phone"));
            address_tv_details.setText(
                    data.getStringExtra("ProvinceName")
                            + data.getStringExtra("CityName")
                            + data.getStringExtra("RegionName")
                            + data.getStringExtra("DetailAddress"));
            String strId = data.getStringExtra("Id");
            addressId = Integer.valueOf(strId);
        }
    }
}
